/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#ifndef MODULESFACTORY_HPP
#define MODULESFACTORY_HPP

#include <map>
#include <boost/thread/mutex.hpp>
#include "cpputils/CppUtils.hpp"
#include "cpputils/dynmod/IModule.hpp"

namespace cpputils {
	namespace dynmod {

		/**
		 * Modules factory provide a support for loading/unloading modules which represents the shared libraries like .dll/.so/.dylib
		 * @note This is a singleton. Please use getInstance() method for access to instance.
		 * @par Usage:
		 * @code
		 * // Dynamically loading and initialization module (dll/dylib/so)
		 * IModule::SharedPtr myModule = ModulesFactory::getInstance()->loadModule ( "MyModule" );
		 *
		 * // Creataing user object instance
		 * MyClass* class = myModule->createModuleObject<MyClass> ();
		 * ...
		 * @endcode
		 * @sa TestDynmod as module sample
		 */
		class ModulesFactory {
			static ModulesFactory m_oInstance;

			typedef boost::unordered_map<std::string,IModule::SharedPtr> Modules;
			Modules m_aLoadedModules;
			boost::mutex m_mxLoadedModules;


			ModulesFactory();
			virtual ~ModulesFactory();

			std::string getLibraryNameForModule(
				const std::string& sModuleName,
				const std::string& sLibraryName
			);

			IModule::SharedPtr loadModuleFromLibrary(
				const std::string& sModuleName,
				const std::string& sVersion,
				const std::string& sLibraryName
			);

		public:

			CPPU_DLLPRFX static ModulesFactory* getInstance();

			CPPU_DLLPRFX IModule::SharedPtr loadModule(
				const std::string& sModuleName,
				const std::string& sVersion=cpputils::libraryVersion.getVersionAsStr(),
				const std::string& sLibraryName=""
			);
			CPPU_DLLPRFX void unloadModule(IModule::SharedPtr poModule);

			CPPU_DLLPRFX void purgeAllModules();
		};
	}
}

#endif // MODULESFACTORY_HPP
